package com.hnit.controllers;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.hnit.service.OrdersService;
import com.hnit.service.PaymentService;
import com.hnit.web.DTO.OrdersDTO;
import com.hnit.web.Utils.OrderStatus;
import com.hnit.web.Utils.ResponseResult;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/payment")
@AllArgsConstructor
@Slf4j
public class PaymentController {
    private final PaymentService paymentService;
    private final OrdersService ordersService;

    /**
     * 创建支付宝订单并返回二维码HTML
     */
    @PostMapping("/alipay/create")
    public String createAlipayOrder(@RequestParam  String orderId) {
        try {
            log.info("创建支付宝订单，订单ID：{}", orderId);

            // 1. 查询订单信息
            OrdersDTO order = ordersService.getOrderById(Long.valueOf(orderId));
            if (order == null) {
                throw new RuntimeException("订单不存在");
            }

            if (!order.getOrderStatus().equals(OrderStatus.PENDING_PAYMENT.getCode())) {
                throw new RuntimeException("订单状态不正确，当前状态：" + order.getOrderStatus());
            }

            // 2. 调用支付宝接口创建订单
            String qrCodeHtml = paymentService.createAlipayOrder(order);

            log.info("支付宝订单创建成功，订单ID：{}", orderId);
            return qrCodeHtml;

        } catch (Exception e) {
            log.error("创建支付宝订单失败，订单ID：{}，错误：{}", orderId, e.getMessage(), e);
            return generateErrorHtml("创建支付订单失败：" + e.getMessage());
        }
    }

    /**
     * 查询支付状态
     */
    @GetMapping("/status/{orderId}")
    public ResponseResult queryPaymentStatus(@PathVariable String orderId) {
        try {
            log.info("查询支付状态，订单ID：{}", orderId);

            boolean isPaid = paymentService.queryPaymentStatus(orderId);

            return ResponseResult.ok().setData(isPaid ? 1 : 0);

        } catch (Exception e) {
            log.error("查询支付状态失败，订单ID：{}，错误：{}", orderId, e.getMessage(), e);
            return ResponseResult.error("查询支付状态失败");
        }
    }

    /**
     * 支付宝异步通知接口（可选）
     */
    @PostMapping("/alipay/notify")
    public String handleAlipayNotify(HttpServletRequest request) {
        try {
            log.info("收到支付宝异步通知");

            // 获取支付宝POST过来的反馈信息
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                String[] values = requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
                }
                params.put(name, valueStr);
            }

            // 验证并处理通知
            if (paymentService.verifyAndHandleNotify(params)) {
                return "success";
            } else {
                return "failure";
            }

        } catch (Exception e) {
            log.error("处理支付宝异步通知失败：{}", e.getMessage(), e);
            return "failure";
        }
    }

    /**
     * 生成错误页面HTML
     */
    private String generateErrorHtml(String errorMsg) {
        return "<div style='text-align:center; padding:50px;'>" +
                "<h2 style='color:red;'>支付失败</h2>" +
                "<p>" + errorMsg + "</p>" +
                "</div>";
    }
}